<template>
    <div>

        <!-- 搜索功能 -->
        <div class="search-header">
            <div class="search-input-container">
                <div class="search-input-icon">
                    <i class="fas fa-search"></i>
                </div>
                <input type="text" class="search-input-field" placeholder="搜索新闻、话题" v-model="searchQuery.title"
                    @keyup.enter="handleSearch()" />
                <div class="search-input-clear" v-show="searchQuery" @click="clearSearch()">
                    <i class="fas fa-times-circle"></i>
                </div>
            </div>
            <button class="search-button" @click="handleSearch()">搜索</button>
        </div>

        <!-- 内容区域 -->
        <div class="content" v-loading="isLoading">
            <!-- 搜索框历史 -->
            <div class="search-history" v-show="!showResults">
                <div v-if="searchHistory.length != 0" class="search-history-header">
                    <div class="search-history-title">搜索历史</div>
                    <div class="search-history-clear" @click="clearHistory()">清空</div>
                </div>

                <!-- 添加暂无搜索历史提示 -->
                <div class="search-no-history" v-if="searchHistory.length === 0"
                    style="text-align: center;font-size: 14px;color: darkgrey;">
                    暂无搜索历史
                </div>

                <div class="search-history-item" v-for="(historyItem, index) in searchHistory" :key="index"
                    @click="selectHistoryItem(historyItem.query)">
                    <div class="search-history-text">
                        <div class="search-history-icon"><i class="fas fa-history"></i></div>
                        <div>{{ historyItem.query }}</div>
                    </div>
                    <div class="search-history-delete" @click.stop="deleteHistoryItem(index)">
                        <i class="fas fa-times"></i>
                    </div>
                </div>
            </div>

            <!-- 热搜榜 -->
            <div class="search-trending" v-show="!showResults">
                <div class="search-trending-header">
                    <div class="search-trending-title">热搜榜</div>
                </div>

                <div class="search-trending-item" v-for="(trendingItem, index) in trending" :key="index + 'trending'"
                    @click="selectTrendingItem(trendingItem)">
                    <div class="search-trending-rank">{{ index + 1 }}</div>
                    <div class="search-trending-content">
                        <div class="search-trending-text">{{ trendingItem.text }}</div>
                        <div class="search-trending-meta">{{ trendingItem.meta }}</div>
                    </div>
                </div>
            </div>

            <!-- 搜索框结果 -->
            <div class="search-results" v-if="showResults">
                <div class="search-results-header">
                    找到 <span class="search-results-count">{{ resultsCount }}</span> 条相关结果
                </div>

                <div class="news-list">
                    <div class="list-item" v-for="(news, index) in searchResults" @click="navigateToNewsDetails(news)"
                        :key="index + 'result'">
                        <img v-if="news.frontCover" :src="news.frontCover" width="80" height="60"
                            style="border-radius: 6px; object-fit: cover;" />

                        <div class="card-content" style="width: 100%;">
                            <div class="list-item-title">{{ news.title }}</div>
                            <div class="list-item-subtitle">{{ news.subtitle }}</div>
                            <div class="card-meta">
                                <div>{{ news.categoryName }}</div>
                                <div>{{ news.publishTime }}</div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>

            <!-- 无搜索结果 -->
            <div class="search-no-results" v-if="showNoResults">
                <div class="search-no-results-icon">
                    <i class="fas fa-search"></i>
                </div>
                <div class="search-no-results-text">没有找到相关结果</div>
                <div class="search-no-results-hint">请尝试其他关键词或检查拼写</div>
            </div>
        </div>

    </div>

    <div class="foot-bar"></div>
    <Foot activeIcon="Search" />
</template>


<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import Foot from '@/components/Foot.vue';
import { useRouter } from 'vue-router';
import api from '@/api';


const router = useRouter();

// 搜索和状态
const searchQuery = ref({
    title: '',
    current: 1,
    size: 10
});
const showResults = ref(false);
const showNoResults = ref(false);
const resultsCount = ref(0);
const isLoading = ref(false); // 加载状态



// 搜索框历史
const searchHistory = ref(JSON.parse(sessionStorage.getItem('searchHistory')) || []);

// 添加到搜索历史
const addToSearchHistory = (query) => {
    // 移除重复项
    searchHistory.value = searchHistory.value.filter(item => item.query !== query);

    // 添加新记录到数组开头
    searchHistory.value.unshift({
        query,
        timestamp: new Date().getTime()
    });

    // 限制最多10条记录
    if (searchHistory.value.length > 10) {
        searchHistory.value = searchHistory.value.slice(0, 10);
    }

    // 保存到sessionStorage
    sessionStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};


// 热搜榜
const trending = ref([]);

// 获取热搜榜数据
const fetchHotSearchList = async () => {
    try {
        const res = await api.getHotSearchList();
        trending.value = res.data.data.map(item => ({ text: item }));
    } catch (error) {
        console.error('获取热搜榜失败:', error);
    }
};

// 页面加载时获取数据
onMounted(() => {
    fetchHotSearchList();
});

// 搜索功能
const searchResults = ref([]);
const searchNews = async () => {
    if (searchQuery.value.title.trim() === '') return;

    isLoading.value = true;
    try {
        searchQuery.value.title = searchQuery.value.title.trim()
        await new Promise(resolve => {
            setTimeout(resolve,200);
        });
        const res = await api.getNewsInCondition(searchQuery.value);
        searchResults.value = res.data.data.list; // 返回的数据
        
        resultsCount.value = searchResults.value.length; // 更新搜索结果数量
        showResults.value = true;
    } catch (error) {
        console.error('搜索失败:', error);
    } finally {
        isLoading.value = false;
    }
};

// 处理搜索
const handleSearch = async () => {
    searchQuery.value.current = 1;
    searchQuery.value.size = 10;
    if (searchQuery.value.title.trim() !== '') {
        // 添加搜索词到历史记录
        addToSearchHistory(searchQuery.value.title.trim());
        await searchNews();
    }
};

// 点击搜索结果
// 跳转文章详情页
const navigateToNewsDetails = (news) => {
    router.push({
        path: '/NewsDetails',
        query: {
            NewsId: news.id,
            newsCategoryName: news.categoryName
        }
    });
};

// 清空搜索
const clearSearch = () => {
    searchQuery.value.title = '';
    showResults.value = false;
    showNoResults.value = false;

};

// 清空搜索历史
const clearHistory = () => {
    searchHistory.value = [];
    sessionStorage.removeItem('searchHistory');
};
// 删除单条搜索历史
const deleteHistoryItem = (index) => {
    searchHistory.value.splice(index, 1);
    sessionStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
};

// 点击搜索历史项
const selectHistoryItem = (item) => {
    searchQuery.value.title = item;
};

// 点击热搜项
const selectTrendingItem = (item) => {
    searchQuery.value.title = item.text;
    handleSearch();
};
</script>

<style scoped>
.list-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eaeaea;
}

.list-item-image {
    width: 80px;
    height: 60px;
    border-radius: 6px;
    object-fit: cover;
    /* 覆盖图片 */

}

.list-item-title {
    font-size: 16px;
    margin-bottom: 4px;
    padding: 10px;

}

.news-list {
    margin-top: 16px;
}

.card-meta {
    display: flex;
    justify-content: space-between;
    color: #8e8e93;
    font-size: 13px;
    padding: 0 10px 10px 10px;

}

.foot-bar {
    height: 80px;
}

/* 样式保持不变 */
.search-header {
    padding: 16px;
    background-color: #fff;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    /* 添加flex布局 */
    align-items: center;
    /* 垂直居中 */
    gap: 8px;
    /* 添加间距 */
}

.search-input-container {
    position: relative;
    display: flex;
    align-items: center;
    background-color: #e9e9eb;
    border-radius: 10px;
    padding: 10px 16px;
    flex: 1;
    /* 占据剩余空间 */
}

.search-button {
    background-color: #007aff;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;
    white-space: nowrap;
    /* 防止按钮文字换行 */
}

.search-input-icon {
    color: #8e8e93;
    margin-right: 8px;
}

.search-results-header {
    padding-left: 16px;
}

.search-input-field {
    border: none;
    background: transparent;
    width: 80%;
    font-size: 16px;
    outline: none;
}

.search-input-clear {
    position: absolute;
    right: 10px;
    color: #8e8e93;
    margin-left: 8px;
    cursor: pointer;
}

.search-history {
    margin-top: 16px;
}

.search-history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px 8px;
    border-bottom: 1px solid #eaeaea;
}

.search-history-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.search-history-clear {
    color: #007aff;
    font-size: 14px;
}

.search-history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #eaeaea;
}

.search-history-text {
    display: flex;
    align-items: center;
}

.search-history-icon {
    color: #8e8e93;
    margin-right: 12px;
}

.search-history-delete {
    color: #8e8e93;
}

.search-trending {
    margin-top: 24px;
}

.search-trending-header {
    padding: 0 16px 8px;
    border-bottom: 1px solid #eaeaea;
}

.search-trending-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.search-trending-item {
    display: flex;
    padding: 12px 16px;
    border-bottom: 1px solid #eaeaea;
}

.search-trending-rank {
    font-size: 16px;
    font-weight: 700;
    color: #ff3b30;
    width: 24px;
    text-align: center;
    margin-right: 12px;
}

.search-trending-content {
    flex: 1;
}

.search-trending-text {
    font-size: 16px;
    margin-bottom: 4px;
}

.search-trending-meta {
    font-size: 12px;
    color: #8e8e93;
}

.search-results {
    /* 删除 display: none; */
    margin-top: 16px;
}

.search-no-results {
    /* 删除 display: none; */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 16px;
    text-align: center;
}

.search-no-results-icon {
    font-size: 48px;
    color: #c7c7cc;
    margin-bottom: 16px;
}

.search-no-results-text {
    font-size: 16px;
    color: #8e8e93;
    margin-bottom: 8px;
}

.search-no-results-hint {
    font-size: 14px;
    color: #8e8e93;
}
</style>